package com.dt.jpa.service.impl;

import com.dt.jpa.bean.UserInfoES;
import com.dt.jpa.dao.UserInfoESDao;
import com.dt.jpa.service.UserInfoServiceES;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class UserInfoServiceESImpl implements UserInfoServiceES {
    @Autowired
    private UserInfoESDao userInfoESDao;

    @Override
    public boolean insert(UserInfoES userInfoES) {
        boolean falg=false;
        try{
            userInfoESDao.save(userInfoES);
            falg=true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return falg;
    }

    @Override
    public List<UserInfoES> search(String searchContent) {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(searchContent);
        System.out.println("查询的语句:"+builder);
        Iterable<UserInfoES> searchResult = userInfoESDao.search(builder);
        Iterator<UserInfoES> iterator = searchResult.iterator();
        List<UserInfoES> list=new ArrayList<UserInfoES>();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }



    @Override
    public List<UserInfoES> searchUser(Integer pageNumber, Integer pageSize,String searchContent) {
        // 分页参数
        Pageable pageable = new PageRequest(pageNumber, pageSize);
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(searchContent);
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(builder).build();
        System.out.println("查询的语句:" + searchQuery.getQuery().toString());
        Page<UserInfoES> searchPageResults = userInfoESDao.search(searchQuery);
        return searchPageResults.getContent();
    }



}
